package com.hkzhao.reportingsystem.config;

import com.hkzhao.reportingsystem.component.JwtAuthenticationTokenFilter;
import com.hkzhao.reportingsystem.component.RestAuthenticationEntryPoint;
import com.hkzhao.reportingsystem.component.RestfulAccessDenieddHandler;
import com.hkzhao.reportingsystem.dto.AdminUserDetail;
import com.hkzhao.reportingsystem.mbg.model.Adminuser;
import com.hkzhao.reportingsystem.mbg.model.Doctor;
import com.hkzhao.reportingsystem.mbg.model.UserPermission;
import com.hkzhao.reportingsystem.service.AdminUserService;
import com.hkzhao.reportingsystem.service.DoctorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.List;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private RestfulAccessDenieddHandler restfulAccessDenieddHandler;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    private AdminUserService adminUserService;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and() //关闭session 因为使用 token 没必要
                .authorizeRequests()
                .antMatchers(HttpMethod.GET,       "/",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/swagger-resources/**",
                        "/v2/api-docs/**")//允许对静态资源的五授权访问
                .permitAll()
                .antMatchers("/doctor/register","/doctor/getvalidcode","/normalUser/**"
                            ,"/manage/login","/doctor/login")
                .permitAll()
                .antMatchers(HttpMethod.OPTIONS)//跨域请求先进行一次options
                .permitAll()
                .anyRequest()
                .authenticated();
        //禁用缓存
        http.headers().cacheControl();
        //添加JWT filter
        http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定义未授权和未登录结果返回
        http.exceptionHandling()
                .accessDeniedHandler(restfulAccessDenieddHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService())
                    .passwordEncoder(passwordEncoder());
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
   @Bean
    public UserDetailsService userDetailsService(){
        return username->{
            Adminuser adminuser = adminUserService.getAdminUserByusername(username);
            if(adminuser!=null) {
                List<UserPermission> permissionList = adminUserService.getPermissionList(adminuser.getTokenId());
                String password  = adminUserService.getPassword(username);
                return new AdminUserDetail(adminuser,permissionList,password);
            }throw new UsernameNotFoundException("用户名或者密码错误");
        };
    }
    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
        return new JwtAuthenticationTokenFilter();
    }
}
